package com.jhgsys.internal.common.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.jhgsys.internal.common.exception.AppInterceptorException;
import com.jhgsys.internal.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class AppInterceptor implements HandlerInterceptor {


    /**
     * 签名属性名
     */
    private final String signField = "sign";
    /**
     * 随机盐属性名
     */
    private final String saltField = "salt";
    /**
     * 签名常量盐
     */
    private final String appCommonSignSalt = "chic_jhs_app_common";
    /**
     * 签名常量盐
     */
    private final String appSignSalt = "chic_jhs_app";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            if ("OPTIONS".equals(request.getMethod())) {
                return true;
            }
            //拦截地址
            String appCommonUrl = "/app/common/";
            String appVerifyUrl = "/app/verify/";
            //接口访问地址（接口权限）
            String requestURI = request.getRequestURI();
            Map<String, String> signMap = new HashMap<String, String>();
            String signValue = request.getHeader(signField);
            String salt = request.getHeader(saltField);
            String appUserId = request.getHeader("appUserId");
            String appUserKey = request.getHeader("appToken");
            Date date = new Date();
            //#region第一步获取签名相关数据
            if(requestURI.indexOf(appVerifyUrl) > -1 ){
                signMap.put("adminId", appUserId);
                signMap.put("signSalt", appSignSalt);
            }else if (requestURI.indexOf(appCommonUrl) > -1 ){
                signMap.put("signSalt", appCommonSignSalt);
            }else{
                log.error("签名验证失败,未获取到用户信息，接口地址：" + requestURI);
                throw new AppInterceptorException(HttpStatus.NOT_FOUND, "未知访问地址");
            }
            signMap.put("salt", salt);
            //#endregion

            //#region 开始签名验证
            if(requestURI.indexOf(appVerifyUrl) > -1 ) {
                if (StringUtils.isBlank(appUserId)) {
                    log.error("签名验证失败,未获取到用户信息，接口地址：" + requestURI);
                    throw new AppInterceptorException(HttpStatus.UNAUTHORIZED, "签名验证失败,未获取到用户信息");
                }
            }
            if (StringUtils.isBlank(signValue)) {
                log.error("签名验证失败,未获取到签名参数或签名值，接口地址：" + requestURI);
                throw new AppInterceptorException(HttpStatus.UNAUTHORIZED, "签名验证失败,未获取到签名参数或签名值");
            }
            String signStr = MapUtil.sortJoin(signMap, "&", "=", false, StrUtil.EMPTY);
            //加密格式：参数字符串 + ddMMyyyy（日期）
            String checkSgin = DigestUtils.md5DigestAsHex((signStr + DateUtil.getDateFormat(date, "ddMMyyyy")).getBytes(StandardCharsets.UTF_8));

            if (!checkSgin.equals(signValue)) {
                log.error("签名验证失败,签名异常，接口地址：" + requestURI);
                throw new AppInterceptorException(HttpStatus.UNAUTHORIZED, "签名验证失败,签名异常");
            }
            //#endregion
            //#region 校验用户状态
            if(requestURI.indexOf(appVerifyUrl) > -1 ) {
//            EnterpriseUser  enterpriseUser = enterpriseUserService.getById(adminId);
//            if (null == enterpriseUser){
//                log.error("用户信息异常，未找到用户。接口地址："+requestURI);
//                throw new MxtInterceptorException(HttpStatus.UNAUTHORIZED,"用户信息异常,未找到用户");
//            }
//
//            if (!"1".equals(enterpriseUser.getStatus()) || !SystemConstant.VALID.equals(enterpriseUser.getDeleteFlg())){
//                log.error("用户信息异常，账号已禁用。接口地址："+requestURI);
//                throw new MxtInterceptorException(HttpStatus.UNAUTHORIZED,"用户信息异常,账号已禁用");
//            }
//
//            if (!adminKey.equals(enterpriseUser.getWebKey()) ){
//                log.error("用户信息异常，登录信息已过期。接口地址："+requestURI);
//                throw new MxtInterceptorException(HttpStatus.UNAUTHORIZED,"用户信息异常,登录信息已过期");
//            }
            }
            //#endregion
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw ex;
        }
        return true;
    }
}